AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

function ENT:Initialize()

	self.Entity:SetModel( "models/as_ship/as_ship.mdl" )
	
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )

	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(25000)
		phys:EnableGravity(false)
		phys:EnableMotion(true)
	end
	
	self.destroyed = false
	self.selfDestruct = false
	self.destroyTimer = CurTime()
	
end

function ENT:Destruct()

	local shipGibs = {}
	for i = 1, 3 do
		shipGibs[i] = ents.Create("prop_physics")
		shipGibs[i]:SetPos(self:GetPos())
		shipGibs[i]:SetAngles(self:GetAngles())
	end
	--Ship Middle
	shipGibs[1]:SetModel("models/as_ship/as_ship_gib1.mdl")
	--Ship Right
	shipGibs[2]:SetModel("models/as_ship/as_ship_gib2.mdl")
	--Ship Left
	shipGibs[3]:SetModel("models/as_ship/as_ship_gib3.mdl")
	
	timer.Simple(6, function() for i = 1, 3 do shipGibs[i]:Remove() end end)
	
	local effData = EffectData()
	effData:SetOrigin(self:GetPos())
	effData:SetScale(self:BoundingRadius() * 1000)
	effData:SetMagnitude(self:BoundingRadius() * 1000)
	util.Effect("Explosion", effData)
	
	shipGibs[1]:Spawn()
	shipGibs[2]:Spawn()
	shipGibs[3]:Spawn()
	
	self:Remove()
	
	for i = 1,3 do
		local rndVel = Vector(math.Rand(-1,1),math.Rand(-1,1),math.Rand(-1,1))
		local rndAng = Angle(math.Rand(-1,1),math.Rand(-1,1),math.Rand(-1,1))
		local rndVal = math.random(210,420)
		shipGibs[i]:GetPhysicsObject():AddAngleVelocity(rndAng * rndVal)
		shipGibs[i]:GetPhysicsObject():SetVelocity((rndVel * rndVal) + self:GetVelocity())
		shipGibs[i]:GetPhysicsObject():EnableGravity(false)
		shipGibs[i]:SetCollisionGroup(COLLISION_GROUP_NONE)
	end
	
end

function ENT:Think()
	
	if !ValidEntity(self.owner) and !self.selfDestruct then
		self.selfDestruct = true
		self.destroyTimer = CurTime() + 5
	end
	
	if ValidEntity(self.owner) then
		self.selfDestruct = false
	end
	
	if self.selfDestruct and (CurTime() > self.destroyTimer) then
		self:Destruct()
	end

end

function ENT:PhysicsCollide(data, physobj)

	if !(data.HitEntity:GetClass() == "laser_shot" or data.HitEntity:GetClass() == "asteroid") then return end
	
	if data.HitEntity:GetClass() == "laser_shot" and !(self.owner == data.HitEntity.owner) then return end
	
	print("Destroyed by " .. tostring(data.HitEntity))
	
	self.destroyed = true
	
end

